<?php

declare(strict_types=1);

namespace So;

use Hyperf\DbConnection\Model\Model as BaseModel;
use Hyperf\ModelCache\Cacheable;
use Hyperf\ModelCache\CacheableInterface;
use Hyperf\Database\Schema\Schema;

/**
 * Model的基类
 * @author Saopig <1306222220@qq.com>
 */
abstract class Model extends BaseModel implements CacheableInterface
{
    use Cacheable;

    protected $dateFormat = 'U';

    protected $hidden = ['deleted_at'];

    protected $connection = 'default';

    protected $fillable = [];

    protected $casts = [];

    /**
     * 排序字段
     * @var sort
     */
    public $sortPk = 'id';

    /**
     * 排序类型
     * @var order
     */
    public $sortBy = 'desc';

    /**
     * 分页显示数量
     * @var pageSize
     */
    public $pageSize = 10;

    /**
     * 可操作的字段
     * @var operate
     */
    public $operate = ['status'];

    /**
     * 快捷搜索字段
     * @var search
     */
    public $searchCloumn = ['id', 'name', 'title', 'username'];

    /**
     * 转换时间戳的字段
     * @var timestampsCloumns
     */
    public $timestampsCloumns = ['created_at', 'updated_at', 'deleted_at', 'endt_at'];

    /**
     * 关联模型的方法名称
     * @var array
     */
    public $withMethods = [];

    /**
     * 获取主键
     * @return string
     */
    public function getPk()
    {
        return $this->primaryKey;
    }

    /**
     * 查找所有孩子主键
     * @param $data
     * @param string $parent_pk
     * @param null $pk
     * @param array $array
     * @return array|mixed
     */
    public function getChildPk($data, $parent_pk = 'pid', $pk = null, $array = [])
    {
        !is_array($data) && $data = [$data];
        !$pk && $pk = $this->getPk();
        foreach ($data as $v) {
            $child = $this::query()->where($parent_pk, '=', $v)->pluck($pk)->toArray();
            if ($child) $array = array_merge($array, $this->getChildPk($child, $parent_pk, $pk, $child));
        }
        return $array;
    }

    /**
     * 获取当前所有字段名
     * @return array
     */
    public function getCloumns(): array
    {
        return Schema::getColumnListing($this->table);
    }

}
